package com.mspersonalized.circumscribedAPI.service;

import com.mspersonalized.circumscribedAPI.utils.HttpUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AlyRlthService {
    @Value("${aly.AppCode.rlth}")
    private String appcode;

    @Resource
    private AlyRxfgService alyRxfgService;

    public String rlth(MultipartFile fileOld, MultipartFile fileNew) {
        String host = "https://picread.market.alicloudapi.com";
        String path = "/facecg";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("srca", alyRxfgService.convertFileToBase64(fileOld));
        bodys.put("srcb", alyRxfgService.convertFileToBase64(fileNew));
        bodys.put("type", "pic");
        bodys.put("effect", "master");


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.getEntity().getContent());
            // 访问JSON字段
            String msg = jsonNode.get("msg").asText();
            String status = jsonNode.get("status").asText();

            /*System.out.println("status: " + status);
            System.out.println("msg: " + msg);*/
            log.info(status+":"+msg);

            return msg;
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return host;
    }
}
